package com.gsocket.client;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientSingle {

    private int port;
    private String host;

    private Socket socket;

    //@Setter
    //private Receiver receiver;
    //
    //@Setter
    //@Getter
    //private int id;

    public ClientSingle(int port, String host) {
        this.port = port;
        this.host = host;
        socket = new Socket();
    }

    public void connect() throws IOException {
        socket.setSoTimeout(5000);
        socket.connect(new InetSocketAddress(host, port));

    }

    public boolean isClosed() {
        return socket.isClosed();
    }

    public byte[] send(byte[] message) throws IOException {
        InputStream is = socket.getInputStream();
        socket.getOutputStream().write(message);

        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int ch;
        ch = is.read(buffer);
        bytestream.write(buffer, 0, ch);
        byte[] data = bytestream.toByteArray();
        //if (receiver != null) {
        //    receiver.receive(data);
        //}
        bytestream.close();
        return data;
    }

    public void close() {
        try {
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public byte[] send(String message) throws IOException {
        return send(message.getBytes(StandardCharsets.UTF_8));
    }
}
